#include "utils.h"
#include <string.h>
#include <stdlib.h>

void bitstring_to_bytes(const char *bitstring, uint8_t *bytes, size_t *byte_len) {
    size_t bitlen = strlen(bitstring);
    size_t blen = (bitlen + 7) / 8;
    *byte_len = blen;

    // Calculate the number of leading zeros needed for the last byte.
    size_t padding = (8 - (bitlen % 8)) % 8; // 计算需要在左边补多少个0
	size_t adjusted_index1 = -padding;


    for (size_t i = 0; i < blen; ++i) {
        bytes[i] = 0;
        for (size_t j = 0; j < 8 ; ++j) {
            // Adjust index to account for leading zeros on the left side.

            if (bitstring[adjusted_index1] == '1'&& adjusted_index1>=0) {
                bytes[i] |= (1 << (7 - j));
            }
            adjusted_index1++;
        }
    }
}

void bytes_to_bitstring(const uint8_t *bytes, size_t byte_len, char *bitstring) {
    for (size_t i = 0; i < byte_len; ++i) {
        for (size_t j = 0; j < 8; ++j) {
            bitstring[i * 8 + j] = (bytes[i] & (1 << (7 - j))) ? '1' : '0';
        }
    }
    bitstring[byte_len * 8] = '\0'; // 确保字符串以null终止
}

void int_to_bytes(uint32_t value, uint8_t *bytes) {
    for (int i = 0; i < 4; ++i) {
        bytes[i] = (value >> (8 * (3 - i))) & 0xFF;
    }
}

uint32_t bytes_to_int(const uint8_t *bytes) {
    uint32_t result = 0;
    for (size_t i = 0; i < 4; ++i) {
        result |= ((uint32_t)bytes[i]) << (8 * (3 - i));
    }
    return result;
}
